package com.shushan.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;


/**
 * @ClassName: OnePiexlActivity
 * @Desciption: 1像素Activity
 * @author: yichaohua
 * @date: 2018-05-26
 */
public class OnePiexlActivity extends BaseActivity{

    private static final String TAG = "OnePiexlActivity";

    private BroadcastReceiver endReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG,"onCreate()");

        //设置1像素
        Window window = getWindow();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        WindowManager.LayoutParams params = window.getAttributes();
        params.x = 0;
        params.y = 0;
        params.height = 1;
        params.width = 1;
        window.setAttributes(params);

        //结束该页面的广播
        endReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                finish();
            }
        };

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(endReceiver, new IntentFilter(
                Constants.ONE_PIX_FINISH_RECEIVER_ACTION));

        //检查屏幕状态
        checkScreen();
    }

    @Override
    protected void onResume() {
        super.onResume();

        checkScreen();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.d(TAG,"onDestroy()");

        if(endReceiver != null && !isDestroyed()){
            unregisterReceiver(endReceiver);
            endReceiver = null;
        }
    }

    /**
     * 检查屏幕状态  isScreenOn为true  屏幕“亮”结束该Activity
     */
    private void checkScreen() {

        PowerManager pm = (PowerManager) OnePiexlActivity.this.getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();
        Log.d(TAG,"isScreenOn=" + isScreenOn);
        if (isScreenOn) {
            finish();
        }
    }

}
